<template>
  <div>
    <Card>
      <p slot="title" class="card-title">
        <Icon type="home"></Icon>
        <span>线索查询</span>
      </p>
      <div>
        <template>
          <Form ref="search" :model="search" :label-width="90">
            <Row>
              <Col span="5">
                <FormItem label="关键字：" prop="name">
                  <Input style="width: 200px" v-model="search.name" placeholder="姓名或者手机号码"></Input>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="分配状态：" prop="status" v-if="managerFlag||adminFlag">
                  <Select v-model="search.status" style="width:200px">
                    <Option value="All">全部</Option>
                    <Option value="N">未分配</Option>
                    <Option value="Y">已分配</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="5" v-if="adminFlag">
                <FormItem label="企业管理员：" prop="manager" :label-width="90">
                  <Select
                    v-model="search.manager"
                    style="width:200px"
                    :filterable="true"
                    @on-change="changeManager()"
                  >
                    <Option value>全部</Option>
                    <Option
                      :value="item.value"
                      v-for=" item in searchManagers"
                      :key="item.value"
                    >{{item.label}}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="5" v-if="managerFlag||adminFlag">
                <FormItem label="分配坐席：" prop="assigneTo">
                  <Select v-model="search.assigneTo" style="width:200px" :filterable="true">
                    <Option value>全部</Option>
                    <Option
                      :value="item.value"
                      v-for=" item in searchAssigneTos"
                      :key="item.value"
                    >{{item.label}}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="5" v-if="managerFlag||adminFlag">
                <FormItem label="线索分组：" prop="groupId">
                  <Select v-model="search.groupId" style="width:200px" :filterable="true">
                    <Option value>全部</Option>
                    <Option
                      :value="item.value"
                      v-for=" item in searchGroups"
                      :key="item.value"
                    >{{item.label}}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="呼叫状态：" prop="callStatus">
                  <Select
                    v-model="search.callStatus"
                    style="width:200px"
                    :on-change="changeCallStatus()"
                  >
                    <Option value>全部</Option>
                    <Option value="N">未拨打</Option>
                    <Option value="Y">已拨打</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="拨打结果：" prop="calledStatus">
                  <Select
                    v-model="search.calledStatus"
                    :value="search.calledStatus"
                    style="width:200px"
                    :disabled="'Y'!=search.callStatus"
                  >
                    <Option value>全部</Option>
                    <Option value="N">未呼通</Option>
                    <Option value="Y">已呼通</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="呼叫结果：" prop="callResult">
                  <Select v-model="search.callResult" style="width:200px">
                    <Option value>全部</Option>
                    <Option
                      :value="item.value"
                      v-for=" item in searchCallResult"
                      :key="item.value"
                    >{{item.label}}</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="导入时间:" prop="startDate">
                  <DatePicker
                    format="yyyy-MM-dd"
                    type="date"
                    placeholder="开始时间"
                    :editable="false"
                    v-model="search.startDate"
                    @on-change="search.startDate=$event"
                    :options="endDateoptions"
                    style="width:200px"
                  ></DatePicker>
                </FormItem>
              </Col>
              <Col span="4">
                <FormItem :label-width="0" prop="endDate">
                  <DatePicker
                    format="yyyy-MM-dd"
                    type="date"
                    placeholder="结束时间"
                    v-model="search.endDate"
                    @on-change="search.endDate=$event"
                    :editable="false"
                    style="width:200px"
                    :options="endDateoptions"
                  ></DatePicker>
                </FormItem>
              </Col>

              <Col span="5">
                <FormItem label="分配时间:" prop="assigneStartDate">
                  <DatePicker
                    format="yyyy-MM-dd"
                    type="date"
                    placeholder="开始时间"
                    :value="search.assigneStartDate"
                    :editable="false"
                    @on-change="search.assigneStartDate=$event"
                    :options="endDateoptions"
                    style="width:200px"
                  ></DatePicker>
                </FormItem>
              </Col>
              <Col span="4">
                <FormItem :label-width="0" prop="assigneEndDate">
                  <DatePicker
                    format="yyyy-MM-dd"
                    type="date"
                    :value="search.assigneEndDate"
                    placeholder="结束时间"
                    @on-change="search.assigneEndDate=$event"
                    :editable="false"
                    style="width:200px"
                    :options="endDateoptions"
                  ></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <FormItem>
                <Button type="primary" @click="clueData=initTableData();getClueList()">查詢</Button>
                <Button style="margin-left: 8px" @click="reset('search');">重置</Button>
                <Button style="margin-left: 8px" @click="download()">
                  <Icon type="ios-cloud-download-outline" />下载线索
                </Button>
              </FormItem>
            </Row>
          </Form>
        </template>
      </div>
      <div>
        <Table
          stripe
          ref="modalTable"
          :columns="columns1()"
          :data="clueData.data"
          style="height:520px"
          :highlight-row="true"
          @on-row-click="rowClick"
        >
          <template slot-scope="{ row }" slot="assignedAt">
            <strong>{{ row.assignedAt?"已分配":"未分配" }}</strong>
          </template>
          <template
            slot-scope="{ row }"
            slot="lastCallStatus"
          >{{ row.lastCallStatus?row.lastCallStatus.name:"" }}</template>
          <template
            slot-scope="{ row }"
            slot="lastCallResult"
          >{{ row.lastCallResult?row.lastCallResult.name:"" }}</template>
          <template slot-scope="{ row }" slot="phone">
            <a @click="openHistory(row)">{{ row.phoneEncty }}</a>
          </template>
          <!-- <template slot-scope="{ row }" slot="action">
           <Button type="primary" size="small" style="margin-right: 5px" >View</Button>
            <Button type="error" size="small">Delete</Button>
          </template>-->
        </Table>

        <Page
          :total="clueData.total"
          size="small"
          show-total
          show-elevator
          class="tr"
          @on-change="pageChange"
          :current.sync="clueData.current"
          :page-size="clueData.size"
        ></Page>
      </div>
    </Card>
    <CallHistory v-if="historyFlag" @cancel="cancelHistory" :clue="currentClue"></CallHistory>
  </div>
</template>
<script>
import { baseUrl } from "@/libs/axios-cfg";
import { checkRole, allRoles } from "@/libs/util";
import CallHistory from "../components/callHistory.vue";

export default {
  data() {
    return {
      search: {
        calledStatus: "N"
      },
      searchCallStatus: [],
      searchCallResult: [],
      searchManagers: [],
      searchGroups: [],
      searchAssigneTos: [],
      historyFlag: false,
      currentChoose: "",
      columns1: () => {
        var objs = [
          {
            key: "id",
            title: "选择",
            width: 60,
            align: "center",
            render: (h, params) => {
              let currentClue = params.row;
              let flag = false;
              if (this.currentClue.id === currentClue.id) {
                flag = true;
              } else {
                flag = false;
              }
              let self = this;
              return h("div", [
                h("Checkbox", {
                  props: {
                    value: flag
                  },
                  on: {
                    "on-change": () => {
                      self.currentClue = currentClue;
                    }
                  }
                })
              ]);
            }
          },
          { title: "客户名称", key: "name" },
          { title: "电话号码", slot: "phone" },
          { title: "备注", key: "remark", tooltip: true },
          { title: "导入时间", key: "createdAt", elseFlag: this.salesFlag },
          { title: "线索分组", key: "groupName" },
          { title: "分配状态", slot: "assignedAt", elseFlag: this.salesFlag },
          { title: "分配坐席", key: "assignedName", elseFlag: this.salesFlag },
          { title: "分配时间", key: "assignedAt" },
          { title: "最新呼叫时间", key: "lastCallAt" },
          { title: "最新呼叫状态", slot: "lastCallStatus" },
          { title: "最新呼叫结果", slot: "lastCallResult" },
          { title: "最新通话备注", key: "lastRemark", tooltip: true }
          // { title: "操作", slot: "action" }
        ];
        var returnObjs = [];
        objs.forEach(k => {
          if (!k.elseFlag) {
            returnObjs.push(k);
          }
        });
        return returnObjs;
      },
      clueData: this.initTableData(),
      endDateoptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      access: [],
      adminFlag: false,
      managerFlag: false,
      salesFlag: false,
      currentClue: {}
    };
  },

  methods: {
    initTableData() {
      return {
        data: [],
        current: 1,
        size: 10
      };
    },
    pageChange() {
      this.getClueList();
    },

    getClueList() {
      var url = "/clue/query/{pageNo}";
      var ps = {};
      ps = Object.assign(ps, this.search);

      this.post(url, ps, { pageNo: this.clueData.current }).then(res => {
          this.$store.commit("setRouteParam", {
            params: Object.assign({}, ps),
            routeName:  this.$route.name
          });
        if (this.checkIsSsuccess(res)) {
          this.clueData.data = res.data.content;
          this.clueData.total = res.data.totalElements;
          this.clueData.totalPages = res.data.totalPages;
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 0,
            closable: true
          });
        }
      });
    },
    getQueryConfig() {
      var url = "/clue/getQueryConfig";

      this.post(url, {}, {}).then(res => {
        if (this.checkIsSsuccess(res)) {
          this.searchManagers = res.data.managers ? res.data.managers : [];
          this.searchAssigneTos = res.data.assigneTos
            ? res.data.assigneTos
            : [];
          this.searchGroups = res.data.groups ? res.data.groups : [];
          this.searchCallStatus = res.data.callStatus
            ? res.data.callStatus
            : [];
          this.searchCallResult = res.data.callResult
            ? res.data.callResult
            : [];
          this.getClueList();
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    },
    changeCallStatus(value) {
      if ("Y" != this.search.callStatus) {
        this.search.calledStatus = "";
      }
    },
    reset(name) {
      this.$refs[name].resetFields();
      this.search = {};
    },
    download() {
      var ps = "";
      for (var key in this.search) {
        ps +=
          "&" + key + "=" + (this.search[key] == null ? "" : this.search[key]);
      }
      var url = baseUrl + "/clue/download?downLoadId=" + sessionStorage.token;
      url += ps;
      window.open(url, "_blank");
    },
    openHistory(row) {
      this.currentClue = row;
      this.historyFlag = true;
    },
    cancelHistory() {
      this.historyFlag = false;
    },
    rowClick(data, index) {
      // this.$refs.modalTable.toggleSelect(index);
      this.currentClue = data;
    },
    changeManager() {
      if (!this.search.manager) {
        this.searchAssigneTos = [];
        this.searchGroups = [];
        return;
      }
      var url = "/clue/getQueryConfig/{id}";
      this.post(url, {}, { id: this.search.manager }).then(res => {
        if (this.checkIsSsuccess(res)) {
          this.searchAssigneTos = res.data.assigneTos
            ? res.data.assigneTos
            : [];
          this.searchGroups = res.data.groups ? res.data.groups : [];
        } else {
          this.$Message.error({
            content: res["msg"],
            duration: 3,
            closable: true
          });
        }
      });
    }
  },
  created() {
    this.salesFlag = checkRole(allRoles.sales);
    this.managerFlag = checkRole(allRoles.manager);
    this.adminFlag = checkRole(allRoles.admin);
    this.getQueryConfig();
    var routeName = this.$route.name;
    var obj = Object.keys(this.$route.params).length>0?this.$route.params:this.$store.state.app.tagParams[routeName];
    if (obj&&Object.keys(obj).length>0) {
      this.search = obj;
    }
  },
  components: {
    CallHistory
  }
};
</script>

